var util = require('../../utils/util.js');

var WxParse = require('../../wxParse/wxParse.js');

var app = getApp();

var screnn_w = 320;


var dataall;
var loadingMore = false;

var page = 1;
var hasMore = true;
var messagetmp = '';

Page({
  data: {
    util: util,
    isShow: false,
    page: 1,
    uid: '',
    token: '',
    data: [],
    noData: false,
    pinSign: 0,
    postuid: '',
    hasLoadding: false,
    allcata: [],
    nowcata: [],
    content_item_w: 100,
    goodTypeView_w: 100,
    colorSet: '',
    goodsList: [],
    goodsDataList: [],
    currcata: 0,

    gwc_count: 0,
    gcataid: "",
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    allGoodsDataArray: '',
    selectCata: '',
    selectIndex: 0
  },

  postuid: '',

  onLoad: function (options) {
    console.log("options", options);
    this.postuid = options.postuid? options.postuid : '';
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      options: options,
    });

    loadingMore = false;

    page = 1;
    hasMore = true;

    var titlename = tc == 1 ? options.title_f : options.title;

    wx.setNavigationBarTitle({
      title: titlename,
    });


    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function (responseData) {
        app.isShow = responseData.data.isShow;
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    wx.getSystemInfo({
      success: function (res) {

        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screnn_w: res.windowWidth,
          content_w: res.windowWidth - 78,
          goodTypeView_w: (res.windowWidth - 78) / 3
        });

      }
    })

    //获取颜色配置
    app.getColorSetData(function (color) {
      var col = color.goods_col ? parseInt(color.goods_col) : 3;
      col = col > 0 ? col : 3;
      that.setData({
        colorSet: color,
        content_item_w: (that.data.content_w - (col + 1) * 5) / col,
        goodTypeView_w: screnn_w / 3
      })
      that.resetNavColor();
    });

    this.setData({
      postuid: options.uid ? options.uid : '',
      pinSign: options.pin ? options.pin : 0
    });



    var inviteuid = options.inviteuid;
    util.api({
      data: {
        "tc": that.data.tc,
        "publickey": util.publiccode,
        "ac": "goodstype"
      },
      success: function (responseData) {
        console.log("所有商品分类", responseData.data);
        var goodsType = responseData.data;
        var goodId = options.cataid;

        console.log("传入的商品分类id：", goodId);

        if (goodId == "0") {
          if (!goodsType.msg) {
            dataall = goodsType;

            that.setData({
              allGoodsDataArray: dataall,
              selectCata: dataall[0],
              selectIndex: 0,
              gcataid: dataall[0]['goods_id'],
              nowcata: dataall[0].child
            });

            that.getAllGoodsData();

          } else {
            wx.hideLoading();
          }
        } else {

          if (!goodsType.msg) {
            let selIndex = 0;
            for (var i = 0; i < goodsType.length; i++) {
              var gid = goodsType[i].goods_id;
              console.log("===gid===!:" + gid);
              if (goodId == gid) {
                selIndex = i;
                break;
              }
            }

            that.setData({
              allGoodsDataArray: dataall,
              selectCata: dataall[selIndex],
              selectIndex: selIndex,
              nowcata: dataall,
              gcataid: goodId,
            });

            that.getAllGoodsData();

          } else {
            wx.hideLoading();
          }
        }

      }
    });
    that.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    });


  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },


  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      path = path.slice(6);
    }
    if (path) {
      wx.reLaunch({
        url: path,
      })
    }
  },

  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    return {
      title: '',
      path: '/pages/goodslist/goodslist?&inviteuid=' + inviteuid + '&cataid=' + that.data.gcataid + '&title=' + that.data.options.title + '&title_f=' + that.data.options.title_f
    };
  },

  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    var that = this;
    that.updateSwiperHeight();
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  pageScrollToBottom: function () {
    var that = this;
    wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.bottom
      });
      that.setData({
        scrollTop: rect.bottom
      })
      console.log("pageScrollToBottom", rect.bottom)
    }).exec()
  },

  updateSwiperHeight: function () {
    var that = this;
    var minheight = that.data.windowHeight - 110;
    var heightnow = that.data.goodsList.length * 135
    that.setData({
      swiper_h: heightnow > minheight ? heightnow : minheight
    })
    console.log("swiper_h", that.data.swiper_h)

  },

  bindPickerSelType: function (e) {
    console.log("选择的分类：", e);
    let selIndex = parseInt(e.detail.value);
    let selGTypeOb = this.data.allGoodsDataArray[selIndex];
    this.setData({
      selectCata: selGTypeOb,
      selectIndex: selIndex,
      gcataid: selGTypeOb.goods_id
    })
    this.getAllGoodsData();
  },

  //载入所有商品
  getAllGoodsData: function () {
    console.log("getAllGoodsData")
    var that = this;
    wx.showLoading({
      title: that.data.tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });
    var id = that.data.gcataid
    that.loadFenleiGoodsData(id, 1);
    
  },

  loadFenleiGoodsData: function (goodsId, index) {
    console.log("loadFenleiGoodsData")
    var that = this;
    
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      // toporder: '1',
      ordernum: 1,//按排序字段排序 0和不传是不安这个排，1是升序，2是降序
      tc: that.data.tc,
      orgid: util.orgid,
      gtype: goodsId,
      // zhiding: '1',
      postuid: that.postuid,
      page: index,
      num: 10
    };
    console.log("商品参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("商品数据" + goodsId + ": ", result);
        if (result.msg) {
          hasMore = false;
          if (index <= 1) {
            that.setData({
              noData: true
            });
          };

        } else {
          result.forEach(function (n, j) {
            n.message = app.parseHTMLText(n.message);
            var nodes = WxParse.getImgurls('detailMessage', 'html', n.message, that, 12).nodes;
            console.log("nodes:", nodes)

            that.whileNodes(nodes);
            console.log(messagetmp)
            n.message = messagetmp;
            messagetmp = ''
          })

          if (index <= 1) {
            that.setData({
              goodsDataList: result
            })
          } else {
            let oldData = that.data.goodsDataList;
            let alldata = oldData.concat(result);
            that.setData({
              goodsDataList: alldata
            })
          }

        }

        loadingMore = false;
        if (that.data.goodsDataList.length <= 0) {
          that.setData({
            noData: true
          });
        };
        console.log("商品数据", that.data.goodsDataList);
        wx.hideLoading();
      }
    });
  },

  // 购物车商品选择数数据
  getGwcData: function (data) {
    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    gwc_datas.forEach(function (m, i) {
      for (var j = 0; j < data.length; j++) {
        var n = data[j];
        if (0 && n.guigelist) {
          for (var k = 0; k < n.guigelist.length; k++) {
            if (m.selGuige.id == n.guigelist[k].id) {
              n.guigelist[k].selectednum = m.buycount;
            }

          }

        } else {
          if (m.id == n.id) {
            n.selectednum = m.buycount;

          }
        }
      }
    })
    return data
  },



  whileNodes: function (n) {
    var that = this
    for (let i = 0; i < n.length; i++) {
      if (n[i].node && n[i].node == "text") {
        console.log("text:", n[i].text)
        messagetmp += n[i].text
        return;
      }
      if (n[i].nodes) {
        console.log("whileNodes:", n[i].nodes)
        that.whileNodes(n[i].nodes);
      }
    }

  },


  loadMore: function (e) {
    var that = this;
    console.log("hasMore", hasMore);
    console.log("loadingMore", loadingMore);
    if (hasMore && !loadingMore) {
      loadingMore = true;
      page++;
      console.log("page", page);
      var id = that.data.gcataid
      that.loadFenleiGoodsData(id, page);
    } else {
      console.log("没有更多了");
    }

  },


})